//
//  SeamphoreDemo.m
//  MultiperThreadTest02
//
//  Created by FelixYin on 2020/4/5.
//  Copyright © 2020 FelixYin. All rights reserved.
//

#import "SeamphoreDemo.h"

/*
 
 1.使用信号量 可以控制线程并发访问的最大数量
 
 */

@interface SeamphoreDemo ()

@property (nonatomic,strong) dispatch_semaphore_t seamphore;
@property (nonatomic,strong) dispatch_semaphore_t moneySeamphore;
@property (nonatomic,strong) dispatch_semaphore_t ticketSeamphore;

@end

@implementation SeamphoreDemo

- (instancetype)init
{
    self = [super init];
    if (self) {
        self.seamphore = dispatch_semaphore_create(3); //初始化为3时，最多同时3个并发队列访问test方法
        self.moneySeamphore = dispatch_semaphore_create(1); //初始化为1时，最多同时1个并发队列访问
        self.ticketSeamphore = dispatch_semaphore_create(1); //初始化为1时，最多同时3个并发队列访问
        
    }
    return self;
}

- (void)saveMoney{
    dispatch_semaphore_wait(self.moneySeamphore, DISPATCH_TIME_FOREVER);
    [super saveMoney];
    dispatch_semaphore_signal(self.moneySeamphore);
}

- (void)drawMoney{
    dispatch_semaphore_wait(self.moneySeamphore, DISPATCH_TIME_FOREVER);
    [super drawMoney];
    dispatch_semaphore_signal(self.moneySeamphore);
}

- (void)saleTicket{
    dispatch_semaphore_wait(self.ticketSeamphore, DISPATCH_TIME_FOREVER);
    [super saleTicket];
    dispatch_semaphore_signal(self.ticketSeamphore);
}

- (void)test {
    for (int i = 0; i < 20; i++) {
        [[[NSThread alloc] initWithTarget:self selector:@selector(remove) object:nil] start];
    }
}

- (void) remove{
    //每次最多3个线程访问
    /*
     原理：
     当信号量的值>0时，就让信号量的值减1，然后继续往下执行代码。当信号量的值小于等于0的时候，就会休眠等待（DISPATCH_TIME_FOREVER），知道信号量的值大于0时，继续信号量的值减1，然后往下执行代码
      
     
     */
    dispatch_semaphore_wait(self.seamphore, DISPATCH_TIME_FOREVER);
    sleep(3);
    NSLog(@"移除操作 === %@",[NSThread currentThread]);
    
    //让信号量加1
    dispatch_semaphore_signal(self.seamphore);
}

@end
